package com.proactive.webapp.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class FacebookConnection {
	private static final String CLIENT_ID = "1003640789663368";
	private static final String CLIENT_SECRET = "8f783566125739e47d61a0b58f7a8f6b";
//	private static final String REDIRECT_URI = "http%3A%2F%2www.proactive.tw%2FfbCheckLogin";// 按下同意後導回的頁面
	private static final String REDIRECT_URI = "http://www.proactive.tw/fbCheckLogin";// 按下同意後導回的頁面
	private static final String SCOPE = "public_profile, email";
	private String accessToken = "";// 不可使用static，會記住
	
//	private static final String CLIENT_ID = "832658393461931";
//	private static final String CLIENT_SECRET = "b26f519a44284ad5b1b2ad9bec8f6f34";
//	private static final String REDIRECT_URI = "http://localhost:8080/Proactive/fbCheckLogin";
	

	public String getOAuthUrl() {
		String url = "http://www.facebook.com/dialog/oauth?client_id="
				+ CLIENT_ID + "&redirect_uri=" + REDIRECT_URI + "&scope="
				+ SCOPE;
		return url;
	}

	public String getGraphUrl(String code) {
		String url = "https://graph.facebook.com/oauth/access_token?client_id="
				+ CLIENT_ID + "&redirect_uri=" + REDIRECT_URI
				+ "&client_secret=" + CLIENT_SECRET + "&code=" + code;
		return url;
	}

	public String getAccessToken(String code) {
		if (accessToken.equals("")) {
			URL graphUrl = null;

			try {
				graphUrl = new URL(getGraphUrl(code));

				URLConnection urlConn = null;
				StringBuffer stringbuffer = null;
				try {
					urlConn = graphUrl.openConnection();
					BufferedReader reader;
					reader = new BufferedReader(new InputStreamReader(
							urlConn.getInputStream()));
					String data;
					stringbuffer = new StringBuffer();
					while ((data = reader.readLine()) != null) {
						stringbuffer.append(data + "\n");
					}
					reader.close();
					accessToken = stringbuffer.toString();
				} catch (IOException e) {
					e.printStackTrace();
				}
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (accessToken.startsWith("{")) {
			throw new RuntimeException("ERROR: Access Token Invalid"
					+ accessToken);
		}
		return accessToken;
	}

}
